<?php

use \Workerman\Worker;
require_once __DIR__."/Workerman/Autoloader.php";


$w = new Worker('websocket://0.0.0.0:9999');
$w->count = 1;

$cli_list = [];

$w->onConnect = function($connection) {
    global $cli_list;

    $ip = $connection->getRemoteIp();
    foreach ($cli_list as $conn) {
        $conn->send("系统消息: ". $ip.'上线了!');
    }

    $cli_list[$ip] = $connection;
    echo "count: ", count($cli_list), PHP_EOL;
    echo $ip.' connect!';
};

$w->onMessage = function($connect, $data) {
    global $cli_list;
    // echo $data, PHP_EOL;
    // $connect->send("WorkerMan Recv: ".$data);

    $ip = $connect->getRemoteIp();
    foreach ($cli_list as $key => $conn) {
        echo 'send '.$key, PHP_EOL;
        $conn->send($ip.': '.$data);
    }
};

$w->onClose = function($connect) {
    global $cli_list;

    $ip = $connect->getRemoteIp();
    unset($cli_list[$ip]);
    foreach ($cli_list as $conn) {
        $conn->send("系统消息: ". $ip.'下线了!');
    }

};

Worker::runAll();

